package com.chunxiadong.config;


import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.Http11NioProtocol;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.stereotype.Component;


@Component
public class CustomContainer implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
    @Value("${https.port}")
    private int httpsPort;
    @Value("${server.port}")
    private int serverPort;
    @Value("${server.ssl.key-store}")
    private String keystoreFile;
    @Value("${server.ssl.key-store-type}")
    private String keystoreType;
    @Value("${server.ssl.key-store-password}")
    private String keystorePass;

    @Override
    public void customize(ConfigurableServletWebServerFactory factory) {
        ((TomcatServletWebServerFactory)factory).addConnectorCustomizers(new TomcatConnectorCustomizer() {
            @Override
            public void customize(Connector httpsconnector) {
                httpsconnector.setPort(httpsPort);
                httpsconnector.setSecure(true);
                httpsconnector.setScheme("https");
                Http11NioProtocol protocol = (Http11NioProtocol) httpsconnector.getProtocolHandler();
                protocol.setMaxConnections(200);
                protocol.setMaxThreads(200);
                protocol.setSelectorTimeout(3000);
                protocol.setSessionTimeout(3000);
                protocol.setConnectionTimeout(3000);
                protocol.setSSLEnabled(true);
                protocol.setKeystoreFile(keystoreFile);
                protocol.setKeystorePass(keystorePass);
                protocol.setKeystoreType(keystoreType);

                Connector httpconnector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
                httpconnector.setPort(serverPort);
                httpconnector.setScheme("http");
                httpconnector.setSecure(false);
                httpconnector.setRedirectPort(httpsPort);
                ((TomcatServletWebServerFactory)factory).addAdditionalTomcatConnectors(httpconnector);
            }
        });


    }
}
